package com.ohuang.socket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;


/**
 * 通过socket实现http请求
 * 仅支持Get请求 不支持https协议
 */

public class SocketHttp {
    private int PORT = 80;
    private String HOST = "127.0.0.1";
    private String HostName = "www.baidu.com";
    private String Uri = "";

    public static void main(String[] args) throws Throwable {
        SocketHttp socketHttp = new SocketHttp();
        String s = socketHttp.getBody("http://www.baidu.com");
        System.out.println(s);

    }

    public String getBody(String url) throws IOException {
        String s = get(url);
        String[] strings=s.split("\r\n\r\n");
        StringBuilder stringBuilder=new StringBuilder();
        for (int i = 1; i <strings.length ; i++) {
            stringBuilder.append(strings[i]);
        }
        return stringBuilder.toString();
    }

    public String get(String url) throws IOException {

        String[] strings = url.split("/");
        String[] hosts = strings[2].split(":");
        HostName = hosts[0];
        if (hosts.length == 2) {
            PORT = Integer.parseInt(hosts[1]);
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 3; i < strings.length; i++) {
            stringBuilder.append(strings[i]);
            stringBuilder.append('/');
        }
        if (stringBuilder.length() > 0) {
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
        }
        Uri = stringBuilder.toString();
        String ip = getDNS(HostName);//dns解析
        if (ip != null) {
            HOST = ip;
        }
        String response = getHttp();
        return response;
    }

    private String getDNS(String name) {
        try {
            InetAddress address = InetAddress.getByName(name);
            return address.getHostAddress();
        } catch (Exception e) {
            System.out.println(e.toString());
            System.exit(1);
            return null;
        }
    }

    private void getAllDNS() {
        try {
            InetAddress[] address = InetAddress.getAllByName("www.baidu.com");
            for (int i = 0; i < address.length; i++) {
                System.out.println(address[i].getHostAddress());
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            System.exit(1);
        }
    }

    private String getHttp() throws IOException {
        Socket socket = new Socket(HOST, PORT);
        PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                socket.getOutputStream(), "UTF-8")), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
        InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream(), "UTF-8");

        printWriter(printWriter);


        char[] chars = new char[1024];
        StringBuilder stringBuilder = new StringBuilder();
        int len = 0;
        while ((len = inputStreamReader.read(chars, 0, 1024)) != -1) {
            stringBuilder.append(chars, 0, len);

        }


        return stringBuilder.toString();
    }

    private void receiveMsg(BufferedReader in) {
        String receiveMsg = "";

        try {
            while (true) {
                if ((receiveMsg = in.readLine()) != null) {

                    System.out.println(receiveMsg);

                }
            }
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

    private void printWriter(PrintWriter printWriter) {
        String s = "GET /" + Uri + " HTTP/1.1\r\n" +
                "Host:" + HostName + "\r\n" +
                "Connection:close\r\n" +
                "\r\n";

        printWriter.println(s);

    }

}
